package site.marqstree.latte.core.delegates.web.client;

import android.graphics.Bitmap;
import android.os.Handler;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import site.marqstree.latte.core.app.ConfigKeys;
import site.marqstree.latte.core.app.Latte;
import site.marqstree.latte.core.delegates.IPageLoadListener;
import site.marqstree.latte.core.delegates.web.WebDelegate;
import site.marqstree.latte.core.delegates.web.route.Router;
import site.marqstree.latte.core.storage.LattePreference;
import site.marqstree.latte.core.ui.loader.LatteLoader;
import site.marqstree.latte.core.util.log.LatteLogger;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.core.delegates.web.client
 * 文件名: WebViewClientImpl
 * 创建者: marqstree
 * 创建时间: 2020/1/31 15:37
 * 描述: TODO
 */
public class WebViewClientImpl extends WebViewClient {

    private final WebDelegate DELEGATE;
    private IPageLoadListener mIPageLoadListener = null;
    private static final Handler HANDLER = Latte.getHandler();

    public WebViewClientImpl(WebDelegate delegate) {
        this.DELEGATE = delegate;
    }

    public void setPageLoadListener(IPageLoadListener listener) {
        this.mIPageLoadListener = listener;
    }

    //任何web页面内的跳转都要走该方法
    @Override  //WebView代表是当前的WebView
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

        String url = request.getUrl().toString();
        LatteLogger.d("shouldOverrideUrlLoading", url);
        //创建新的含WebView的Fragment替换原来含WebView的Fragment
        //若原来的Fragment有父Fragment(带底部Tab导航按钮的Fragment)，则替换父Fragment
        //返回true:表示在当前的WebView继续打开网页
        return Router.getInstance().handleWebUrl(DELEGATE, url);
    }

    //载入页面前事件
    //1）调用回调接口
    //2）开启无限转圈进度对话框
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if (mIPageLoadListener != null) {
            mIPageLoadListener.onLoadStart();
        }
        LatteLoader.showLoading(view.getContext());
    }

    //载入页面后事件
    //1）调用回调接口
    //2）关闭无限转圈进度对话框
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //拦截webview的cookie，并存入sp
        // 待原生的okhttp3 api发起http请求时，将webview中cookie附加到原生http请求头中
        syncCookie();
        if (mIPageLoadListener != null) {
            mIPageLoadListener.onLoadEnd();
        }
        HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                LatteLoader.stopLoading();
            }
        }, 1000);
    }

    //将http请求的cookie存入sp
    //注意：此处的http请求是WebView发起的
    // 待原生的okhttp3 api发起http请求时，将webview中cookie附加到原生http请求头中
    // 使得原生http api也能跨域向web服务器发请求
    private void syncCookie(){
        final CookieManager manager = CookieManager.getInstance();
        final String webHost = Latte.getConfiguration(ConfigKeys.WEB_HOST);
        if(webHost != null) {
            if(manager.hasCookies()) {
                final String cookieStr = manager.getCookie(webHost);
                if (cookieStr != null && !cookieStr.equals("")) {
                    LattePreference.addCustomAppProfile("cookie", cookieStr);
                }
            }
        }

    }

}
